import _ from 'lodash';
import {useState} from 'react';

const useDragList = () => {
    const [data, setData] = useState([] as any);
    const [loading, setLoading] = useState(false);

    const getItem = (target: any, dragBefore: any, dragAffter: any) => {
        const newAfter = _.cloneDeep(dragAffter);
        const newBefore = _.cloneDeep(dragBefore);
        // 推进
        if (_.keys(newAfter).includes('children')) {
            return _.forEach(target, (item, index) => {
                if (item.key === newAfter.key && !item.isNew) {
                    newBefore.isNew = true;
                    item.children.push(newBefore);
                }
                else {
                    getItem(item?.children, newBefore, newAfter);
                }
            });
        }
        else {
            // 插入
            let count = 0;
            return _.forEach(target, (item, index) => {
                if (item.key === newAfter.key && !item?.isNew) {
                    newBefore.isNew = true;
                    count++;
                    if (count <= 1) {
                        target.splice(index, 0, newBefore);
                    }
                }
                else {
                    getItem(item?.children, newBefore, newAfter);
                }
            });
        }
    };

    // 去除标识
    const restItem = (target: any) =>  _.forEach(target, (item) => {
        if (item?.isNew) {
            delete item?.isNew;
        }
        else {
            restItem(item?.children);
        }
    });

    // 删除某一项
    const deleteItem = (target: any, dragBefore: any) =>
        _.forEach(target, (item, index) => {
            if (item?.key === dragBefore?.key && !item?.isNew) {
                target.splice(index, 1);
            }
            else {
                deleteItem(item?.children, dragBefore);
            }
        });

    // 移动操作
    const moveRow = (dragBefore: number, dragAffter: any) => {
        if (_.isEqual(dragBefore, dragAffter)) {
            return;
        }
        setLoading(true);
        const DragBefore = getItem(data, dragBefore, dragAffter);
        const newData = restItem(deleteItem(DragBefore, dragBefore));
        setData(newData);
        const timer = setTimeout(() => {
            setLoading(false);
        });
        return () => {
            clearTimeout(timer);
        };
    };

    return {loading, data, setData, moveRow};
};

export default useDragList;
